import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author seer
 */
public class CompletableFuturePageQuery {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Map<String, Object> res = pageQuery();
        long end = System.currentTimeMillis();
        System.out.println("查询结果 " + res.get("data") + " count " + res.get("count"));
        System.out.println("耗时 " + (end-start));
        // 687 ms
    }


    public static Map<String, Object> pageQuery() {
        Map<String, Object> res = new HashMap<>();
        try(Connection connection = DriverManager.getConnection(DataSourceConfig.URL, DataSourceConfig.USER, DataSourceConfig.PASS)) {
            CompletableFuture<List<Person>> completableFuture = CompletableFuture.supplyAsync(() -> {
                String sql = "select * from person limit 50000,100";
                List<Person> ps = new ArrayList<>();
                try(PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                    ResultSet resultSet = preparedStatement.executeQuery();
                    while(resultSet.next()) {
                        Person p = new Person();
                        p.setName(resultSet.getString("name"));
                        p.setSex(resultSet.getInt("age"));
                        p.setAddress(resultSet.getString("address"));
                        ps.add(p);
                    }
                    res.put("data", ps);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return ps;
            });
            CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
                int count = 0;
                String sql2 = "select count(*) c from person";
                try(PreparedStatement preparedStatement2 = connection.prepareStatement(sql2)) {
                    ResultSet resultSet = preparedStatement2.executeQuery();
                    resultSet.next();
                    count = resultSet.getInt("c");
                    res.put("count", count / 50000);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return count;
            });
            completableFuture.thenAcceptBoth(completableFuture1, (a, b) -> {
                res.put("data", a);
                res.put("count", b);
            });
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return res;
    }

}
